package handler

import (
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"net/http"
	"os"
	"path/filepath"
	"post/pkg"
)

func Upload(c *gin.Context) {
	file, err := c.FormFile("file")
	if err != nil {
		return
	}
	ext := filepath.Ext(file.Filename)
	if ext != ".png" && ext != ".jpg" && ext != ".gif" {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    http.StatusBadRequest,
			"message": "图片格式错误",
		})
		return
	}
	if file.Size >= 1024*200 {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    http.StatusBadRequest,
			"message": "图片大小不能超过200kb",
		})
		return
	}
	filename := uuid.NewString() + ".jpg"
	filepath := file.Filename + "./upload/" + filename
	os.Getwd()
	name := filepath + "/upload/" + filename
	err = c.SaveUploadedFile(file, name)
	if err != nil {
		return
	}
	upload, err := pkg.FileUpload(filename)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    http.StatusBadRequest,
			"message": "上传失败",
			"data":    nil,
		})
		return
	}

	os.Remove(filepath)
	c.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "上传成功",
		"data":    upload,
	})
}
